<template>
	<div>
		<div class="container-box" ref="container">
			<Info ref="Info" @setConfig="setConfig"></Info>
			<Content ref="Content"></Content>
		</div>

		<uni-fab
			v-if="state === 'write'"
			ref="fab"
			:pattern="pattern"
			:content="content"
			:horizontal="horizontal"
			:vertical="vertical"
			icon="more-filled"
			@trigger="trigger" />
	</div>
</template>

<script>
	import * as app from '@/api/index.js';
	import * as apis from '@/api/quota/apply/api.js';
	import * as utils from '@/pages/quota/libs/utils.js';
	import Info from './info/index.vue';
	import Content from './content/index.vue';
	import Base64 from '../../libs/base64.js';
	const base64 = new Base64();
	export default {
		name: '',
		components: { Info, Content },
		props: {
			value: {
				required: false,
			},
			from: {
				required: false,
			},
		},
		data() {
			return {
				scrollTop: 0,
				obj: {},
				config: {
					quotationProductSchemeRule: {},
					quotationProductSchemeAttributeOption: {},
				},
				currentStep: 1,
				deptList: {
					company: [], //公司
					department: [], // 组织
					scheme: [], //方案列表
				},
				insuranceList: [], // 商业险险种
				dictList: {
					cityList: [],
				},
				planDicts: {
					levelList: [],
					packagelList: [],
					supplierList: [],
				},

				//按钮
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff',
				},
				content: [
					{
						icon: 'plusempty',
						text: '新增',
						type: 'add',
					},
					{
						icon: 'checkbox',
						text: '暂存',
						type: 'save',
					},
					{ icon: 'checkmarkempty', text: '提交', type: 'submit' },
					// { icon: 'closeempty', text: '调试', type: 'test' },
					{ icon: 'closeempty', text: '验证', type: 'testv' },
				],
				horizontal: 'right',
				vertical: 'bottom',
				query: {},
				state: 'write',
			};
		},
		provide() {
			return {
				details_provide: () => this.obj,
				config_provide: () => this.config,
				deptList_provide: () => this.deptList,
				state_provide: () => this.state,
				insuranceList_provide: () => this.insuranceList,
				dictList_provide: () => this.dictList,
				planDicts_provide: () => this.planDicts,
				fromtype_provide: () => 'edit',
			};
		},
		computed: {},
		onLoad(options) {
			this.$nextTick(() => {
				this.query = options;
				this.init(options);
			});
		},
		mounted() {},
		watch: {},
		created() {
			if (this.from == 'preview') {
				this.state = 'readonly';
			}
			uni.showLoading({
				title: '加载中...',
				mask: true,
			});
		},

		methods: {
			dataload() {
				if (this.from == 'preview') {
					this.obj = this.value;
					this.state = 'readonly';
					this.init({
						from: 'preview',
					});
				}
			},
			trigger({ index, item }) {
				this.$refs.fab.close();
				this.$nextTick(async () => {
					switch (item.type) {
						case 'add':
							this.add();
							break;
						case 'save':
							this.save();
							break;
						case 'submit':
							this.submit();
							break;
						// case 'test':
						// 	console.log(this.obj);
						// 	break;

						case 'testv':
							let vaildResult = await this._validate();
							console.log(vaildResult);
							break;
					}
				});
			},
			add() {
				let lastSequenceNumber =
					this.obj?.productList[this.obj?.productList.length - 1]?.sequenceNumber || 0;
				let sequenceNumber = lastSequenceNumber + 1;
				this.obj.productList.push(this.getProductListDefaultData(sequenceNumber));
			},
			save() {
				console.log(this.obj);
				// return;
				uni.showLoading({
					title: '保存中...',
					mask: true,
				});
				this.allot();
				this.initPlanConf();
				apis.DraftSave(this.obj)
					.then(res => {
						if (res.code == 200) {
							uni.showToast({
								mask: true,
								title: '暂存成功',
								icon: 'success',
							});
							setTimeout(() => {
								let url = `/pages/quota/apply/list/index`;
								this.$tab.redirectTo(url);
							}, 1500);
						}
					})
					.finally(() => {
						uni.hideLoading();
					});
			},
			async submit() {
				console.log(this.obj);
				// 把planConf设置为字符串

				// 公共保险维保部分赋值给每个部分
				this.allot();
				// 测算全部
				let calcResult = await this.calcAll();
				if (!calcResult) return;
				// // 打开所有折叠面板
				// this.openAllCollapse();
				// // scrollTop不设置为0的话，获取到的错误元素的top会不准，会减去当前的scrollTop
				// this.scrollTop = 0;
				setTimeout(async () => {
					let vaildResult = await this._validate();
					if (Array.isArray(vaildResult)) {
						uni.hideLoading();
						uni.showModal({
							mask: true,
							title: '提示',
							content: vaildResult?.[0]?.errorMessage ?? '请完善表单数据',
							showCancel: false,
						});
						return;
					}
					this.initPlanConf(); // 将PlanConf转为字符串，放前边会导致不是个对象，getChangedVal方法全是undefind

					uni.showLoading({
						title: '保存中...',
						mask: true,
					});

					apis.Save(this.obj)
						.then(res => {
							if (res.code == 200) {
								uni.showToast({
									mask: true,
									title: '提交成功',
									icon: 'success',
								});
								setTimeout(() => {
									let url = `/pages/quota/apply/list/index`;
									this.$tab.redirectTo(url);
								}, 1500);
							} else {
								uni.hideLoading();
								throw new Error();
							}
						})
						.catch(err => {
							this.resetPlanConf();
						})
						.finally(() => {});
				}, 300);

				// uni.showLoading({
				// 	title: '验证中...',
				// });
				// let node = await this._scrollToError();
				// if (node) {
				// 	this.scrollTop = node.top;
				// }
			},
			calcAll() {
				return this.$refs.Content.calcAll();
			},
			openAllCollapse() {
				this.$refs.Content?.openAllACollapse?.();
			},
			initPlanConf() {
				this.obj.productList?.forEach(item => {
					if (typeof item.planConf === 'object') {
						item.planConf = JSON.stringify(item.planConf);
					} else {
						item.planConf = '{}';
					}
				});
			},
			resetPlanConf() {
				this.obj.productList?.forEach(item => {
					if (typeof item.planConf === 'string' && item.planConf !== '') {
						item.planConf = JSON.parse(item.planConf);
					} else {
						item.planConf = {};
					}
				});
			},
			recoverPlanConf() {
				this.obj.productList?.forEach(item => {
					if (typeof item.planConf === 'string' && this.notEmpty(item.planConf)) {
						item.planConf = JSON.parse(item.planConf);
					} else {
						item.planConf = {};
					}
				});
			},
			async v() {
				// uni-forms-item__error msg--active
			},
			init(query = {}) {
				this.$nextTick(async () => {
					try {
						this.query = query;
						if (query.from !== 'preview') {
							if (query.from == 'copy') {
								await this.getCopyDetails(query.id);
							} else if (query.from == 'edit') {
								await this.getDetails(query.id);
							} else if (query.from == 'add') {
								this.setDetaultData();
							}
							this._dataload();
						}
						uni.showLoading({
							title: '加载方案中...',
							mask: true,
						});
						this.recoverPlanConf();

						await this.getAuthorizedProductSchemes();
						if (query.from !== 'add') {
							this.setConfig({});
						}
						console.log('obj');
						console.log(this.obj);

						this.$nextTick(() => {
							uni.hideLoading();
						});

						// 获取公司部门
						this.getDeptList(1);
						this.getDeptList(2);
						// 获取商业险险种
						this.getInsuranceList();
						// this.getRegionList();
						// this.getSupplierList();
						this.getLevelList();
						this.getPackagelList();
						// this._clearValidate();
					} catch (error) {
						console.log(error);
						uni.hideLoading();
					}
				});
			},

			recoverPlanConf() {
				this.obj?.productList?.map(item => {
					if (this.notEmpty(item.planConf) && typeof item.planConf == 'string') {
						item.planConf = JSON.parse(item.planConf);
					} else {
						item.planConf = {};
					}
				});
			},
			getCopyDetails(calcSchemeId) {
				return new Promise(resolve => {
					uni.showLoading({
						title: '加载中...',
						mask: true,
					});
					apis?.InfoCopy(calcSchemeId)
						.then(res => {
							if (res.code == 200) {
								this.obj = res.data;
								Reflect.deleteProperty(this.obj, 'contractTemplateList');
								resolve();
							}
						})
						.finally(() => {});
				});
			},
			getDetails(calcSchemeId) {
				return new Promise(resolve => {
					uni.showLoading({
						title: '加载中...',
						mask: true,
					});
					apis?.Details(calcSchemeId)
						.then(res => {
							if (res.code == 200) {
								this.obj = res.data;
								Reflect.deleteProperty(this.obj, 'contractTemplateList');
								resolve();
							}
						})
						.finally(() => {});
				});
			},

			setDetaultData(obj = {}) {
				let detaultData = {
					schemeId: undefined,
					leaseContract: {
						contractTemplateSchemeType: '2',
						contractTemplateType: '1',
					},
					salesContract: null,
					guaranteeContract: null,
					productList: [this.getProductListDefaultData()],
				};
				this.obj = Object.assign(detaultData, obj);
			},
			getProductListDefaultData(sequenceNumber = 0) {
				return {
					sequenceNumber,
					plan: {
						planDriverType: '2',
						planFuelType: '2',
						planPaymentMethodType: this.config.businessSource == '2' ? '2' : undefined,
						planPeriod: this.config.businessSource == '2' ? 0 : undefined,
						planDriverAccessory: undefined,
					},
					maintenanceMileageType: '1',
					insuranceList: [],
					maintenanceList: [],
					attachedDecorationList: [],
					feeList: [],
					planConf: {},
					substituteControlLevelType: '2',
					planConf: {},
				};
			},
			getSupplierList() {
				let params = {
					businessTypeCode: '6',
				};
				apis.SupplierlList(params).then(res => {
					if (res.code == 200) {
						this.planDicts.supplierList = res.data ?? [];
					}
				});
			},
			// 获取报价替代车列表
			getLevelList() {
				apis.LevelList({}).then(res => {
					if (res.code == 200) {
						this.planDicts.levelList = res.data;
					}
				});
			},
			getPackagelList() {
				apis.PackagelList({}).then(res => {
					if (res.code == 200) {
						this.planDicts.packagelList = res.data;
					}
				});
			},
			//城市列表
			getRegionList() {
				regionList({
					regionLevel: 2,
					areaId: null,
				}).then(res => {
					if (res.code == 200) {
						this.dictList.cityList = res.data.filter(e => e.regionLevel === 3);
					}
				});
			},
			// 商业险险种
			getInsuranceList() {
				return new Promise(resolve => {
					apis.Insurance({})
						.then(res => {
							console.log(res);

							if (res.code == 200) {
								this.insuranceList =
									res.data?.map(item => {
										if (Array.isArray(item.coverageAmountList)) {
											item.coverageAmountList = JSON.stringify(
												item.coverageAmountList,
											);
										}
										return item;
									}) ?? [];
							}
						})
						.finally(() => {
							resolve();
						});
				});
			},
			getDeptList(deptType) {
				let params = {
					deptType,
				};
				app.DeptListNoPermission(params).then(res => {
					if (res.code == 200) {
						res?.data?.map(item => {
							item.deptId = item.deptId?.toString();
						});
						switch (deptType) {
							case 1:
								this.deptList.department = res?.data ?? [];
								break;
							case 2:
								this.deptList.company = res?.data ?? [];
								break;
						}
					}
				});
			},
			getAuthorizedProductSchemes() {
				return new Promise((resolve, reject) => {
					uni.showLoading({
						title: '获取方案中...',
						mask: true,
					});
					let businessSource = this.$store.state.user?.userInfo?.businessType;

					let method = apis.AuthorizedProductSchemes;
					if (this.from == 'preview') {
						method = apis.SinglePlan;
					}
					method(this.obj.schemeId)
						.then(res => {
							if (res.code == 200) {
								if (this.from == 'preview') {
									this.deptList.scheme = [res.data];
								} else {
									let configList = [];
									configList = res.data?.filter(item => {
										return true;
										if (this.from == 'preview') {
											return false;
										}
										if (businessSource == '3') {
											return true;
										}

										if (this.obj.schemeId?.toString() === item.id) {
											return true;
										}
										if (item.applicableType?.toString() == '0') {
											return true;
										}
										return item.applicableType == businessSource;
									});

									try {
										if (this.obj?.schemeSnapshootData) {
											let config = JSON.parse(
												base64.decode(this.obj?.schemeSnapshootData),
											);
											if (this.from == 'preview') {
												console.log('有旧方案');
												configList.push(config);
											}
										}
									} catch (error) {
										console.log(error);
									}
									this.deptList.scheme = configList;
								}
								resolve();
							} else {
								reject();
							}
						})
						.catch(() => {})
						.finally(() => {});
				});
			},

			setConfig({ item, type }) {
				// console.log('设置方案中');
				uni.showLoading({
					title: '设置方案中...',
					mask: true,
				});
				let schemeId = this.obj.schemeId;
				let config = {};
				if (type == 'changePlan') {
					config = item ?? {};
					this.setDetaultData({ schemeId });
					this.setDefaultConfig(config);
					this.obj.schemeSnapshootData = base64.encode(JSON.stringify(item));
					// 主动选择方案为空，跳出
					if (this.Empty(item)) {
						uni.hideLoading();
						return;
					}
				} else {
					let scheme = this.deptList.scheme.find(
						e => e.id.toString() == this.obj.schemeId?.toString(),
					);
					config = scheme;
				}
				if (this.notEmpty(config)) {
					this.config = config;
				} else {
					uni.hideLoading();
					this.obj = {
						productList: [this.getProductListDefaultData()],
					};
					uni.showModal({
						content: '未查找到预设产品方案！请重新选择',
						showCancel: false,
					});
					return;
				}
				this.$set(this.obj, 'rentType_raw', this.config.leasingType);
				console.log('config');
				console.log(config);
				// this.infoData.schemeSnapshootData = btoa(JSON.stringify(item));

				// if (this.query.from == 'add') {
				// 	// 产品名称
				// 	this.setDefaultConfig(config);
				// }
				if (type == 'changePlan') {
					uni.hideLoading();
				}
			},
			setDefaultConfig(config) {
				this.$set(this.obj, 'schemeName', config.schemeName);
				// 产品编号
				this.$set(this.obj, 'schemeCode', config.schemeNo);

				this.$set(
					this.obj,
					'rentType',
					this.getRentType(config.businessSource, config.leasingType),
				);

				if (config.applicableType !== 0) {
					this.$set(this.obj, 'sourceBusinessType', config.applicableType?.toString?.());
				} else {
					this.$set(this.obj, 'sourceBusinessType', undefined);
				}
				if (config.vehicleSource?.toString?.() == '1') {
					this.$set(this.obj, 'carType', '1');
					this.$set(this.obj, 'carSourceType', '1');
				}
				if (config.vehicleSource?.toString?.() == '2') {
					this.$set(this.obj, 'carType', '2');
					this.$set(this.obj, 'carSourceType', '2');
				}
				if (config.vehicleSource?.toString?.() == '3') {
					this.$set(this.obj, 'carType', '2');
					this.$set(this.obj, 'carSourceType', '1');
				}
				this.$set(this.obj, 'leaseeId', '1793947084274655233');
				setTimeout(() => {
					this._clearValidate();
				}, 300);
			},
			getRentType(businessSource, leasingType) {
				let reny = '';
				if (businessSource == '1' && leasingType == '1') {
					reny = '3';
				}
				if (businessSource == '1' && leasingType == '2') {
					reny = '4';
				}
				if (businessSource == '2' && leasingType == '1') {
					reny = '1';
				}
				if (businessSource == '2' && leasingType == '2') {
					reny = '2';
				}
				return reny;
			},
			allot() {
				if (this.obj?.productList?.length <= 1) return;
				let productListItem = this.A_deepClone(this.obj?.productList?.[0]);
				this.obj.productList?.forEach((item, index) => {
					if (index >= 1) {
						//购买类型
						item.insuranceBuyType = productListItem.insuranceBuyType;
						//购买方式
						item.insuranceBuyModeType = productListItem.insuranceBuyModeType;
						item.insuranceBuyModeTypeStr = productListItem.insuranceBuyModeTypeStr;
						//保险公司
						item.insuranceCompanyKey = productListItem.insuranceCompanyKey;
						//保险公司
						item.insuranceCompanyVal = productListItem.insuranceCompanyVal;
						//保险标准
						item.insuranceStandardType = productListItem.insuranceStandardType;
						// 外部转租赁保险租期信息
						item.insuranceConfList = this.A_deepClone(
							productListItem.insuranceConfList,
						);
						// 保险列表
						item.insuranceList = this.A_deepClone(productListItem.insuranceList);

						// // 增值服务特约条款
						// item.addedServicesType =
						// 	productListItem.addedServicesType;
						// // 交强险测算金额
						// item.insuranceCompulsoryQuondamAmount =
						// 	productListItem.insuranceCompulsoryQuondamAmount;
						// // 本次交强险金额
						// item.insuranceCompulsoryCurrentAmount =
						// 	productListItem.insuranceCompulsoryCurrentAmount;
						// // 车船税测算金额
						// item.insuranceCarvesselQuondamAmount =
						// 	productListItem.insuranceCarvesselQuondamAmount;
						// // 本次车船税金额
						// item.insuranceCarvesselCurrentAmount =
						// 	productListItem.insuranceCarvesselCurrentAmount;
						// // 商业险测算金额
						// item.insuranceCommercialQuondamAmount =
						// 	this.A_deepClone(
						// 		productListItem.insuranceCommercialQuondamAmount,
						// 	);
						// // 本次商业险金额
						// item.insuranceCommercialCurrentAmount =
						// 	this.A_deepClone(
						// 		productListItem.insuranceCommercialCurrentAmount,
						// 	);
						// // 保险询价附件
						// item.insuranceConsultAccessory = this.A_deepClone(
						// 	productListItem.insuranceConsultAccessory,
						// );
						// // 维保费用（月）
						// item.maintenancePrice = this.A_deepClone(
						// 	productListItem.maintenancePrice,
						// );
						// 年行驶公里数
						item.maintenanceAnnualMileageKey = this.A_deepClone(
							productListItem.maintenanceAnnualMileageKey,
						);
						// 是否包含维保
						item.maintenanceType = this.A_deepClone(productListItem.maintenanceType);
						// 供应商
						item.maintenanceSupplierId = this.A_deepClone(
							productListItem.maintenanceSupplierId,
						);
						item.maintenanceSupplierName = this.A_deepClone(
							productListItem.maintenanceSupplierName,
						);
						// 合同是否限制里程
						item.maintenanceMileageType = this.A_deepClone(
							productListItem.maintenanceMileageType,
						);
						// 维保套餐
						item.maintenanceMealType = this.A_deepClone(
							productListItem.maintenanceMealType,
						);
						// 维保套餐名字
						item.maintenanceMealTypeStr = this.A_deepClone(
							productListItem.maintenanceMealTypeStr,
						);
						// 维保套餐列表
						item.maintenanceList = this.A_deepClone(productListItem.maintenanceList);
						// // 维保费用合计：￥
						// item.maintenanceFee = this.A_deepClone(
						// 	productListItem.maintenanceFee,
						// );
						// 输入框状态快照
						// item.planConf = this.A_deepClone(
						// 	productListItem.planConf,
						// );
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container-box {
		padding-bottom: 170rpx;
	}
</style>
